package net.tensor.skynet

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.fragment_list.*
import kotlinx.coroutines.*
import net.tensor.skynet.adapter.CardAdapter
import net.tensor.skynet.common.user.entity.User
import net.tensor.skynet.entity.DataContainer
import net.tensor.skynet.fragment.GridDemoFragment
import net.tensor.skynet.fragment.ListDemoFragment
import net.tensor.skynet.service.UserService
import net.tensor.skynet.utils.BaseUtils
import net.tensor.skynet.utils.StringToInputStreamTest
import okhttp3.OkHttpClient
import java.io.InputStream
import java.util.*
import javax.net.ssl.SSLContext
import javax.net.ssl.X509TrustManager
import kotlin.coroutines.CoroutineContext

class MainActivity : AppCompatActivity(), View.OnClickListener, CoroutineScope {
    //job用于控制协程,后面launch{}启动的协程,返回的job就是这个job对象
    private lateinit var job: Job
    private var baseUtils: BaseUtils? = null
    private var adapter: CardAdapter? = null

    //=======================
    private var stream: InputStream? = null
    private var trustManager: X509TrustManager? = null
    private var sslContext: SSLContext? = null
    private var okHttpClient: OkHttpClient? = null
    private var gson: Gson? = null
    private var retrofit: UserService? = null
    //=======================

    override fun onDestroy() {
        super.onDestroy()
        //当acitivity结束之后,我们不需要再请求网络了,结束当前协程
        job.cancel()
    }

    //继承CoroutineScope必须初始化coroutineContext变量
    // 这个是标准写法,+其实是plus方法前面表示job,用于控制协程,后面是Dispatchers,指定启动的线程
    override val coroutineContext: CoroutineContext
        get() = job + Dispatchers.Main

    //======================================================================
    private fun initNetwork() {
        job = Job()
        baseUtils = BaseUtils()
        stream = baseUtils!!.getInputStream(this, R.raw.server200)
        trustManager = baseUtils!!.getTrustManager(stream!!)
        sslContext = trustManager?.let { baseUtils!!.getSSLContext(it) }
        okHttpClient =
            sslContext?.let { trustManager?.let { it1 -> baseUtils!!.getOkHttpClient(it1, it) } }
        gson = baseUtils!!.getGson()
        retrofit = okHttpClient?.let {
            baseUtils!!.getRetrofit(
                it,
                "https://192.168.1.200:8080",
                gson ?: Gson()
            )
        }
    }

    //======================================================================
    private var fragment: ListDemoFragment? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        listSample.setOnClickListener(this)
        gridSample.setOnClickListener(this)

        supportFragmentManager.addOnBackStackChangedListener {
            buttonContainer.alpha = if (supportFragmentManager.backStackEntryCount > 0) 0f else 1f
        }
    }

    private external fun stringFromJNI(): String

    companion object {
        init {
            System.loadLibrary("native-lib")
        }
    }

    override fun onClick(view: View) {
        val fragment = when (view.id) {
            R.id.listSample -> ListDemoFragment.instance()
            else -> GridDemoFragment()
        }
        supportFragmentManager.beginTransaction()
            .replace(R.id.container, fragment as Fragment)
            .addToBackStack(null)
            .commit()
    }

    private fun getData(page: Int, pageSize: Int) {
        launch {
            try {
                val map = mutableMapOf<String, Int>()
                map["page"] = page
                map["pageSize"] = pageSize
                val result = withContext(Dispatchers.IO) {
                    retrofit?.queryPage(
                        map
                    )?.execute()
                }
                if (result != null) {
                    if (result.isSuccessful) {
                        DataContainer.pageNum = result.body()?.pageNum ?: 0
                        DataContainer.pageSize = result.body()?.pageSize ?: 0
                        DataContainer.pages = result.body()?.pages ?: 0
                        DataContainer.total = result.body()?.total ?: 0
                        DataContainer.USER_ITEMS = result.body() as ArrayList<User>
                        //recyclerView.adapter?.notifyDataSetChanged()
                        fragment?.recyclerView?.adapter?.notifyDataSetChanged()
                        //recyclerView.adapter?.replaceAll((result.body()?.list as ArrayList<User>))
                    } else {
                        //adapter?.replaceAll(arrayListOf())
                    }
                }
            } catch (e: Exception) {
                //adapter?.replaceAll(arrayListOf())
            }
        }
    }
}